package com.zzyl.nursing.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 入住Service业务层处理
 *
 * @author Katana
 * @Date 2025-05-17
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private IElderService elderService;
    
    @Autowired
    private IBedService bedService;
    
    @Autowired
    private IContractService contractService;
    
    @Autowired
    private ICheckInConfigService checkInConfigService;
    
    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }
    
    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }
    
    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }
    
    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }
    
    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }
    
    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }
    
    /**
     * 根据老人身份证号查询入住信息
     *
     * @param
     * @return
     */
    @Override
    public List<CheckIn> selectCheckInByElderId(String idCardNo, Integer status) {
        
        return checkInMapper.selectCheckInByElderId(idCardNo, status);
    }
    
    /**
     * 入住申请
     *
     * @param dto
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void apply(CheckInApplyDto dto) {
        //1 获取入住信息,确认老人未入住
        List<CheckIn> checkIns = this.selectCheckInByElderId(dto.getCheckInElderDto().getIdCardNo(), 1);
        if (!checkIns.isEmpty()) {
            throw new RuntimeException("老人已入住");
        }
        
        //2 更新床位状态为已入住
        Bed bed = bedService.selectBedById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedService.updateBed(bed);
        
        //3 新增或更新老人信息
        Elder elder = elderService.lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .one();
        if (elder == null) {
            elder = new Elder();
        }
        BeanUtils.copyProperties(dto.getCheckInElderDto(), elder);
        elder.setBedId(dto.getCheckInConfigDto().getBedId());//房间id
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(4);//状态 已入住
        if (elder.getId() == null) {
            elderService.save(elder);
        } else {
            elderService.updateById(elder);
        }
        
        //4 新增签约办理
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        contract.setElderId(elder.getId());//老人id
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());//合同号
        contract.setElderName(elder.getName());//老人姓名
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());//合同开始时间
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());//合同结束时间
        int status = LocalDateTime.now().isBefore(contract.getStartDate()) ? 0 : LocalDateTime.now().isBefore(contract.getEndDate()) ? 1 : 2;
        contract.setStatus(status);//状态
        contractService.save(contract);
        
        //5. 新增入住信息
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkIn);
        checkIn.setElderName(elder.getName());//老人姓名
        checkIn.setElderId(elder.getId()); //老人id
        checkIn.setIdCardNo(elder.getIdCardNo());//老人身份证号
        checkIn.setBedNumber(bed.getBedNumber());//床号
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList())); //家属列表;
        checkIn.setStatus(0);//状态：已入住
        this.save(checkIn);
        
        //6. 新增入住配置
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());//入住ID
        checkInConfigService.save(checkInConfig);
        
        
    }
    
    /**
     * 获取入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        //1 获取入住信息
        CheckIn checkIn = this.selectCheckInById(id);
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //2 查询老人信息
        Elder elder = elderService.selectElderById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        //3 获取入住配置信息
        CheckInConfig checkInConfig = checkInConfigService.lambdaQuery()
                .eq(CheckInConfig::getCheckInId, id)
                .one();
        if (checkInConfig != null) {
            CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
            BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
            checkInConfigVo.setStartDate(checkIn.getStartDate());
            checkInConfigVo.setEndDate(checkIn.getEndDate());
            checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        }
        //4 查询签约办理信息
        Contract contract = contractService.lambdaQuery()
                .eq(Contract::getElderId, checkIn.getElderId())
                .one();
        checkInDetailVo.setContract(contract);
        //5  查询家属信息
        String sanitizedJson = checkIn.getRemark();
        if (!checkIn.getRemark().startsWith("[")) {
            sanitizedJson = "[{\"name\": \"\"} ]";
        }
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(sanitizedJson, ElderFamilyVo.class);
        
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        return checkInDetailVo;
        
    }
}
